import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '',
    nextId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    setInputValue(state, value) {
      state.inputValue = value
    },
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue,
        done: false
      }
      state.list.push(obj);
      state.nextId++;
      state.inputValue = ''
    },
    removeItem(state, id) {
      //根据ID查找对应项的索引
      const index = state.list.findIndex(item => item.id === id);
      if (index !== -1) {
        state.list.splice(index, 1)
      }
    },
    changeStatus(state, obj) {
      const index = state.list.findIndex(item => item.id === obj.id);
      if (index !== -1) {
        state.list[index].done = obj.status
      }
    },
    cleanDone(state) {
      state.list = state.list.filter(e => e.done === false);
    },
    changeViewKey(state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList(context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  getters: {
    unDoneLength(state) {
      return state.list.filter(item => item.done === false).length;
    },
    listByKey(state) {
      if(state.viewKey === 'all') {
        return state.list
      }else if(state.viewKey === 'undone') {
        return state.list.filter(item => item.done === false)
      } else {
        return state.list.filter(item => item.done === true)
      }
    }
  }
})
